package com.Blog.www.servlet;

import com.Blog.www.constant.DataConstant;
import com.Blog.www.constant.PageConstant;
import com.Blog.www.constant.SqlConstant;
import com.Blog.www.constant.TipsConstant;
import com.Blog.www.po.PageBean;
import com.Blog.www.po.User;
import com.Blog.www.service.BlogService;
import com.Blog.www.service.Impl.BlogServiceImpl;
import com.Blog.www.service.Impl.UserServiceImpl;
import com.Blog.www.service.UserService;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;


/**
 * @author 君未洋
 */
@WebServlet("/User/*")
@MultipartConfig
public class UserServlet extends BaseServlet {

    private static UserService service = new UserServiceImpl();
    private static BlogService blogService = new BlogServiceImpl();

    public void banTime(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String[] userIds = req.getParameterValues("userId");
        Integer banTime = Integer.parseInt(req.getParameter("banTime"));
        //直接调用service处理
        req = service.banTime(userIds,banTime,req);
        //封禁完成,直接返回
        req.getRequestDispatcher("User/banTimeList").forward(req,resp);
    }
    public void banTimeList(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //其实类似封禁和解禁

        //获取参数
        String currentPage = req.getParameter("currentPage");
        //当前页码
        String rows = req.getParameter("rows");
        //每页显示条数
        //数据存储
        req.setAttribute(DataConstant.BLOG_A, service.findUserList(currentPage, rows, SqlConstant.STATUS_B , SqlConstant.IDENTITY_B));
        //将数据存入req域后转发
        req.getRequestDispatcher("/timeList.jsp").forward(req, resp);
    }

    /**
     * 来做做听说巨难的图片上传功能
     */
    public void addImg(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //获取上传的用户id
        //获取part对象
        Part part = req.getPart("imgFile");
        User user = (User) req.getSession().getAttribute(DataConstant.USER_A);
        req.removeAttribute(PageConstant.BLOG_G);
        if (service.addImg(part, user)) {
            req.setAttribute(PageConstant.BLOG_G, TipsConstant.BLOG_OPERATION_C);
            User login = service.login(user.getAccount() + "", user.getPassword());
            if (login != null) {
                System.out.println(login);
                login.setFlag(true);
                req.getSession().removeAttribute(DataConstant.USER_A);
                req.getSession().setAttribute(DataConstant.USER_A, login);
            }
        } else {
            req.setAttribute(PageConstant.BLOG_G, TipsConstant.BLOG_OPERATION_A);
        }
        req.getRequestDispatcher("/UserBlog/findUserBlog").forward(req, resp);
    }

    /**
     * 游客返回登录用方法
     */
    public void reLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //把上传的user删除就可以返回登录页面了
        //还是要擦除掉上传的cookie数据,不然还是会有bug
        Cookie[] cs = req.getCookies();
        //获取数据,并遍历
        resp = service.deleteCookie(cs, resp);
        req.getSession().removeAttribute(DataConstant.USER_A);
        req.getRequestDispatcher("/login.jsp").forward(req, resp);
    }

    /**
     * 实现自动登录用的方法
     */
    public void autoLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //获取目前上传到Cookie上的id
        Integer userId = (Integer) req.getSession().getAttribute(SqlConstant.AUTO_LOGIN);
        //获取数据,并遍历
        System.out.println("查询到的id为" + userId);
        User autoUser = service.autoLogin(userId);
        if (autoUser == null) {
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        } else {
            req.getSession().removeAttribute(DataConstant.USER_A);
            req.getSession().setAttribute(DataConstant.USER_A, autoUser);
            req.getRequestDispatcher("/UserBlog/findBlogByPage").forward(req, resp);
        }

    }

    /**
     * 游客登录用方法
     */
    public void touristLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //为用户注册一个账号,用于登录用的游客账号,使用cookie保存一下登录的账号的地址
        User user = service.touristLogin();
        if (user == null) {
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
            return;
        }
        //把账户的id上传到cookie上
        Cookie c = new Cookie(SqlConstant.AUTO_LOGIN, user.getId() + "");
        c.setMaxAge(60 * 60 * 24 * 30);
        //先保存个一个月把

        c.setPath(req.getContextPath());
        //设置作用路径为根路径

        resp.addCookie(c);
        user.setFlag(false);
        req.getSession().removeAttribute(DataConstant.USER_A);
        req.getSession().setAttribute(DataConstant.USER_A, user);

        //发送数据到服务器
        //进入正常页面
        req.getRequestDispatcher("/UserBlog/findBlogByPage").forward(req, resp);
    }

    /**
     * 用户修改密码方法
     */
    public void modifyPassword(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //先获取下现在登录的用户
        String verifyCode = req.getParameter("verifycode");
        //获取下验证码
        String checkCode_server = (String) req.getSession().getAttribute("CHECKCODE_SERVER");
        //获取display验证码
        req.getSession().removeAttribute("CHECKCODE_SERVER");

        if (service.examineCheckCode(req, resp, verifyCode, checkCode_server, PageConstant.USER_A, "/modifyPassword.jsp") == null) {
            return;
        }

        //获取下现在登录的用户
        User user = (User) req.getSession().getAttribute(DataConstant.USER_A);
        //再获取下现在输入的原密码
        String oldPassword = req.getParameter(DataConstant.USER_B);
        String password = req.getParameter(DataConstant.USER_C);

        //都没问题就可以修改密码了
        service.changePassword(user, password, oldPassword, req, resp);
    }

    /**
     * 用户找回密码用方法
     */
    public void recall(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //获取用户上传的用户名和账号
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String account = req.getParameter("account");
        //调用方法查询
        service.recall(username, account, req, resp);
        //将找回密码的用户上传到req上,然后转发到找回页码界面
    }

    /**
     * 用户解禁用方法
     */
    public void noBanUser(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        req.setCharacterEncoding("utf-8");
        //先获取下用户的id
        String[] userIds = req.getParameterValues("userId");
        //校验一下
        if (userIds == null || userIds.length == 0) {
            //返回封禁界面
            //返回数据有误
            req.setAttribute(PageConstant.USER_B, TipsConstant.BLOG_OPERATION_A);
        } else {
            service.changeUser(userIds, SqlConstant.STATUS_B);
            blogService.changeBlog(userIds, SqlConstant.STATUS_B);
            req.setAttribute(PageConstant.USER_B, TipsConstant.BLOG_OPERATION_B);
        }
        req.getRequestDispatcher("/User/noBanUserList").forward(req, resp);
    }

    /**
     * 用户解禁用名单
     */
    public void noBanUserList(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

        //将用户数据列表列出来

        //获取参数
        String currentPage = req.getParameter("currentPage");
        //当前页码
        String rows = req.getParameter("rows");
        //每页显示条数
        PageBean<User> pb = service.findUserList(currentPage, rows, SqlConstant.STATUS_C, SqlConstant.IDENTITY_B);
        //数据存储
        req.setAttribute(DataConstant.BLOG_A, pb);
        req.setAttribute(DataConstant.BLOG_B, "noBan");
        //将数据存入req域后转发
        req.getRequestDispatcher("/userList.jsp").forward(req, resp);
    }

    /**
     * 用户封禁用方法
     */
    public void banUser(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        req.setCharacterEncoding("utf-8");

        //先获取下用户的id
        String[] userIds = req.getParameterValues("userId");
        //校验一下
        req.removeAttribute(PageConstant.USER_B);
        if (userIds == null || userIds.length == 0) {
            //返回数据有误
            req.setAttribute(PageConstant.USER_B, TipsConstant.BLOG_OPERATION_A);
        } else {
            service.changeUser(userIds, SqlConstant.STATUS_C);
            blogService.changeBlog(userIds, SqlConstant.STATUS_C);
            req.setAttribute(PageConstant.USER_B, TipsConstant.BLOG_OPERATION_B);
        }
        req.getRequestDispatcher("/User/banUserList").forward(req, resp);
    }

    /**
     * 用户列表查询用方法
     */
    public void banUserList(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        req.setCharacterEncoding("utf-8");
        //将用户数据列表列出来

        //获取参数
        String currentPage = req.getParameter("currentPage");
        //当前页码
        String rows = req.getParameter("rows");
        //每页显示条数
        //调用servlet
        PageBean<User> pb = service.findUserList(currentPage, rows, SqlConstant.STATUS_B, SqlConstant.IDENTITY_B);

        //数据存储
        req.removeAttribute(DataConstant.BLOG_A);
        req.setAttribute(DataConstant.BLOG_A, pb);
        req.removeAttribute(DataConstant.BLOG_B);
        req.setAttribute(DataConstant.BLOG_B, "ban");
        //将数据存入req域后转发
        req.getRequestDispatcher("/userList.jsp").forward(req, resp);
    }

    /**
     * 管理员登录用方法
     */
    public void managerLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        req.setCharacterEncoding("utf-8");
        //获取当前登录的账号
        User user = (User) req.getSession().getAttribute(DataConstant.USER_A);
        //校验账号的身份
        service.managerLogin(user, req, resp);
    }

    /**
     * 用户登录用方法
     */
    public void login(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //获取数据
        String verifyCode = req.getParameter("verifycode");
        //获取下验证码
        String checkCode_server = (String) req.getSession().getAttribute(DataConstant.USER_D);
        //获取display验证码
        req.getSession().removeAttribute(DataConstant.USER_D);
        if (service.examineCheckCode(req, resp, verifyCode, checkCode_server, PageConstant.USER_C, "/login.jsp") == null) {
            return;
        }
        //获取下登录的用户
        String account = req.getParameter("account");
        String password = req.getParameter("password");

        //顺便获取下要不要自动登录
        String auto = req.getParameter("auto");
        User login = service.login(account, password);
        login.setFlag(true);
        req.removeAttribute(PageConstant.USER_C);
        req = service.examineLogin(req, resp, login, auto);

    }

    /**
     * 注册用
     */
    public void regist(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //获取数据
        String verifyCode = req.getParameter("verifycode");
        //获取下验证码
        String checkCode_server = (String) req.getSession().getAttribute(DataConstant.USER_D);
        //获取display验证码
        req.getSession().removeAttribute(DataConstant.USER_D);
        if (service.examineCheckCode(req, resp, verifyCode, checkCode_server, PageConstant.USER_C, "/regist.jsp") == null) {
            return;
        }

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User regist = service.regist(username, password);
        req.removeAttribute(PageConstant.USER_C);
        req = service.examineRegist(req, resp, regist);

    }


    /**
     * 二维码的显示
     */
    public void checkCode(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        //服务器通知浏览器不要缓存
        resp.setHeader("pragma", "no-cache");
        resp.setHeader("cache-control", "no-cache");
        resp.setHeader("expires", "0");

        //在内存中创建一个长80，宽30的图片，默认黑色背景
        //参数一：长
        //参数二：宽
        //参数三：颜色
        int width = 80;
        int height = 30;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        //获取画笔
        Graphics g = image.getGraphics();
        //设置画笔颜色为灰色
        g.setColor(Color.GRAY);
        //填充图片
        g.fillRect(0, 0, width, height);

        //产生4个随机验证码，12Ey
        String checkCode = service.getCheckCode();
        //将验证码放入HttpSession中
        req.getSession().removeAttribute(DataConstant.USER_D);
        req.getSession().setAttribute(DataConstant.USER_D, checkCode);

        //设置画笔颜色为黄色
        g.setColor(Color.YELLOW);
        //设置字体的小大
        g.setFont(new Font("黑体", Font.BOLD, 24));
        //向图片上写入验证码
        g.drawString(checkCode, 15, 25);

        //将内存中的图片输出到浏览器
        //参数一：图片对象
        //参数二：图片的格式，如PNG,JPG,GIF
        //参数三：图片输出到哪里去
        ImageIO.write(image, "PNG", resp.getOutputStream());
    }
}
